﻿using System;
using System.IO;
using System.Windows.Input;
using LEShortcut.Dialogs.Xaml;
using LEShortcut.Helper;
using LEShortcut.Models.Views;
using LEShortcut.Models.Views.Pages;
using Microsoft.Win32;

namespace LEShortcut.Commands
{
    public class SaveShortcutCommand : ICommand
    {
        public bool CanExecute(object parameter)
        {
            return true;
            //            if (parameter == null) return false;
            //            var context = parameter as HomeViewContext;
            //            return context != null && !string.IsNullOrWhiteSpace(context.ExeutionPath);
        }

        public void Execute(object parameter)
        {
            var context = parameter as HomeViewContext;
            if (context != null)
            {
                if (!string.IsNullOrWhiteSpace(context.ExeutionPath))
                {
                    if (!string.IsNullOrWhiteSpace(context.ChoosedProfile))
                    {
                        var saveDialog = new SaveFileDialog
                        {
                            Title = "ChooseSaveShortcutLocationTitle".GetI18NString(),
                            FileName = context.FileName,
                            DefaultExt = "lnk",
                            AddExtension = true,
                            Filter = "ChooseShortcutFilter".GetI18NString()
                        };
                        bool? showDialog = saveDialog.ShowDialog();
                        if (showDialog != null && (bool) showDialog)
                        {
                            var info = new ShellLinkInfo
                            {
                                ExeutionPath = context.ExeutionPath,
                                Description = context.Description,
                                IconPath = context.IconPath,
                                IconIndex = context.IconIndex
                            };
                            bool result = ShellLinkHelper.SaveShortcut(info, saveDialog.FileName,
                                Path.Combine(context.Config.LePath, "LEProc.exe"), context.ChoosedProfile);
                            if (result) new CreateShortcutSucceedDialog().ShowDialog();
                            else new SaveShortcutFailedDialog().ShowDialog();
                        }
                    }
                    else new ChooseProfileDialog().ShowDialog();
                }
                else new ChooseFileDialog().ShowDialog();
            }
        }

        public event EventHandler CanExecuteChanged;
    }
}